package com.example.weathersuggestion;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.util.Log;


public class LocationList{
	
	
	//private List<Location> locationList;
	private int numLocations;
	private int selectedLocation;
	private Context context;
	private String provider;
	LocationProvider pro;
	private Criteria criteria;
	public LocationManager locationManager;
	//public final LocationListener listener;
	public Location currentLocation;
	Intent intent;
	Geocoder geocoder;
	private String listFileName = "file";
	File file;
	FileOutputStream outputStream;
	FileInputStream in;
	private String homeLocation = "94701";
	private String currentLocationZip;
	
	
	/**
	 * Constructor for LocationList
	 */
	public LocationList(Context c){
		super();
		context = c;

		//data structure to hold Locations
		//locationList = new ArrayList<Location>();
		//number of locations always = 1 (current location)
		numLocations = 1;
		//index of location to be displayed, default 0
		selectedLocation = 0;
		//context = Context.LOCATION_SERVICE;
		//instantiate geocoder
				geocoder = new Geocoder(context,Locale.US);
		//Instantiate LocationManager
		locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
		final LocationListener listener = new LocationListener(){
			//LOCATIONLISTENER
			@Override 
			public void onLocationChanged(Location arg0) {
				// TODO Auto-generated method stub
				//Uses last known location in method
			//	updateCurrentLocation();
				
			}
			
			//LOCATIONLISTENER
			@Override 
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			//LOCATIONLISTENER
			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			//LOCATIONLISTENER
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}
		};	
		
		//Criteria: set Accuracy COARSE
		criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_LOW);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		//Set best location provider
		provider = locationManager.getBestProvider(criteria,true);
		pro = locationManager.getProvider(LocationManager.NETWORK_PROVIDER);
	locationManager.requestLocationUpdates(provider, 0, 0, listener);
		//Call updateCurrentLocation() to instantiate current Location
		updateCurrentLocation();
	//	Log.e("geocode", ""+ currentLocation.getLatitude());
		//Add currentLocation to first index of array
	//	locationManager.removeUpdates(listener);		
		readFile();
	


	}
	
	public void readFile(){
		//Handle reading from file or write the currentLocation zip to file
		//Create file to store location information
		//listFileName = "locationListFile";
		//No file has been created
		
		FileInputStream fis;
		try {
			fis = context.openFileInput("homefile");
			StringBuffer fileContent = new StringBuffer("");

			byte[] buffer = new byte[1024];

			while (fis.read(buffer) != -1) {
			    fileContent.append(new String(buffer));
			}
			homeLocation = fileContent.toString().trim();

		} catch (FileNotFoundException e) {
			homeLocation = "99510";
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void setHome(String s){
		homeLocation = s;
		writeFile();
	}
	
	public void writeFile(){
		FileOutputStream fos;
		try {
			fos = context.openFileOutput("homefile", Context.MODE_PRIVATE);
			fos.write(homeLocation.getBytes());

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
	}
	/** Method to read in the list from a file
	 *  Called in constructor if file does exist
	 */
//	public void populateListFromFile(){
//		//collects zip codes from file, and creates arrayList of Strings
//		ArrayList<String>tempZip = new ArrayList<String>();
//			InputStream is;
//			FileInputStream in;
//			try {
//				in = context.openFileInput(listFileName);
//				
//
//				is = in;
//				
//			} catch (FileNotFoundException e) {
//				Log.e("whut", "why");
//				 is = context.getResources().openRawResource(R.raw.charlotte);
//			}
//			InputStreamReader inputStreamReader = new InputStreamReader(is);
//			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//			String inputString;
//			
//			try {
//				
//				while((inputString = bufferedReader.readLine()) != null){
//					tempZip.add(inputString);
//					
//					
//				}
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			
//		
//
//	
//		//Now populate the list NOTE: Decided to start at 1 because the currentLocation is already handled in constructor and other methods
//		for(int i = 0; i<tempZip.size(); i++){
//			addLocationFromFile(tempZip.get(i));			
//		}		
//	}
	
	/**Method to overwrite file with current information
	 * Needs to be called every time that the list is changed or updated
	 */
//	public void updateFile(){
//		//write current location zip to file
////		try {
////			
////			outputStream = context.openFileOutput(listFileName, Context.MODE_PRIVATE);
////			for(int i = 0; i < locationList.size(); i++){
////			
////				outputStream.write((this.getZipLocation(getLocation(i))+"\n").getBytes());
////				
////			
////			outputStream.close();}
////		} catch (Exception e) {
////			e.printStackTrace();
////		}
//		
//		FileOutputStream fos;
//		try {
//			fos = context.openFileOutput(listFileName, Context.MODE_PRIVATE);
//			for(int i=0; i<locationList.size(); i++){
//				fos.write((this.getZipLocation(getLocation(i))+"\n" ).getBytes());
//				
//			}
//			fos.close();
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	
//		
//	}
	
	/** Create new location from zip in file, doesn't call the updateFile() method like the other add methods
	 * @param String Zip Code
	 * Should only be called from populateListFromFile()
	 */
//	private void addLocationFromFile(String s){
//		List<Address> temp = null;
//
//		Location loc = new Location(provider);
//		try {
//			temp = geocoder.getFromLocationName(s, 3);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		double lat, longi;
//		lat = temp.get(0).getLatitude();
//		longi = temp.get(0).getLongitude();
//		loc.setLatitude(lat);
//		loc.setLongitude(longi);
//		//locationList.add(loc);
//		numLocations++;
//	}
	
	
	

	/** Add location method
	 * @param l Location to be added
	 * @return boolean value if successfully added
	 */
//	public boolean addLocation(Location l){
//		if(l!=null){
//			//too many locations
//	
//			
//			//Add Location to list at index from numLocations
//			locationList.add(l);
//			numLocations++;
//			updateFile(); //updates file with new location
//			return true;
//			
//		}
//		else{
//			return false;
//		}
//	}
	
	/** Getter method to return specific location in list
	 * @param index Index of location in list
	 * @return specified Location object from list
	 */
//	public Location getLocation(int index){
//		try{
//			return locationList.get(index);
//		}
//		catch(IndexOutOfBoundsException e){
//			e.printStackTrace();
//			return null;
//		}
//	}
	
	/** Getter method to find index of a location
	 * @param l Location to find index
	 * @return index value of location
	 */
//	public int getIndexOf(Location l){
//		return locationList.indexOf(l);
//	}
	
	/**
	 * Method to set location to be viewed
	 * @param l
	 * @return index of selected location
	 */
//	public int setSelectedLocation(int index){
//		//if index is in bounds, change selectedLocation
//		if(index>0&&index<locationList.size()){
//			selectedLocation = index;
//			return index;
//		}
//		else{
//			return -1;
//		}
//	}
	
	
	/** Update the current location
	 * @return new currentLocation
	 */
	public void updateCurrentLocation(){
		 LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
		  Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

	//	currentLocation = locationManager.getLastKnownLocation(pro);
	
		currentLocationZip = getZipLocation(location);
			}
	
	/** Create new location
	 * @param String Zip Code/City,State/LatLong
	 * @return Location of entered information 
	 */
	public Location addNewLocation(String s){
	//	Log.d("temp","Hello");
		List<Address> temp;
		Location loc = null;
		try {
			temp = geocoder.getFromLocationName(s, 3);
			loc = new Location(provider);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		double lat, longi;
		lat = temp.get(0).getLatitude();
		longi = temp.get(0).getLongitude();
		loc.setLatitude(lat);
		loc.setLongitude(longi);
		//addLocation(loc);
		numLocations++;
	//	setSelectedLocation(getIndexOf(loc));
		//updateFile(); //update file with new location
		return loc;
	}
	
//	public void removeLocation(int index){
//		
//		if(index!=-1){
//			locationList.remove(index);
//			numLocations--;
//			if(selectedLocation==index){
//				setSelectedLocation(0);
//			}
//		}
//		updateFile(); //updates file with removed location
//	}
	
	public boolean isGPSProviderEnabled(){
		return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}
	
	//Getter method to return zip code of selected location
//	public String getZipSelectedLocation(){
//		String zip = "";
//		List<Address> temp;
//		try{
//			temp = geocoder.getFromLocation(getLocation(currentLocation).getLatitude(),getLocation(selectedLocation).getLongitude(), 1);
//			
//		} catch(IOException e){
//			e.printStackTrace();
//			return null;
//		}
//		zip = temp.get(0).getPostalCode();
//		int i = 5;
//		Log.d("hi", "" + i);
//		return zip;
//	}
//	
	//Getter method to return zip code of selected location
	public String getZipLocation(Location l){
		Geocoder michael = new Geocoder(context, Locale.US);
		String zip = "";
		List<Address> temp = new ArrayList<Address>();
		try {
			temp = michael.getFromLocation(l.getLatitude(),l.getLongitude(), 1);
			zip = temp.get(0).getPostalCode();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	//	Log.e("zipME", ""+l.getLatitude());
		
		//zip = "28223";
		
		return zip;
	}
	
	//Getter method to return city of selected location
//	public String getCitySelectedLocation(){
//		String city = "";
//		List<Address> temp;
//		try{
//			temp = geocoder.getFromLocation(getLocation(selectedLocation).getLatitude(),getLocation(selectedLocation).getLongitude(), 1);
//		} catch(IOException e){
//			e.printStackTrace();
//			return null;
//		}
//		city = temp.get(0).getLocality();
//		return city;		
//	}
//	
	
	//Getter method to return state that corresponds to Location at index in list
//	public String getStateLocation(int index){
//		String state = "";
//		List<Address> temp;
//		try{
//			temp = geocoder.getFromLocation(getLocation(index).getLatitude(),getLocation(index).getLongitude(), 1);
//		} catch(IOException e){
//			e.printStackTrace();
//			return null;
//		}
//		state = temp.get(0).getAdminArea();
//		return state;		
//	}
//	
	//Getter method to return state that corresponds to Location at index in list
//	public String getStateSelectedLocation(){
//		String state = "";
//		List<Address> temp;
//		try{
//			temp = geocoder.getFromLocation(getLocation(selectedLocation).getLatitude(),getLocation(selectedLocation).getLongitude(), 1);
//		} catch(IOException e){
//			e.printStackTrace();
//			return null;
//		}
//		state = temp.get(0).getAdminArea();
//		return state;		
//	}
	
	//Getter method to return city that corresponds to location at index in list
//	public String getCityLocation(int index){
//		String city = "";
//		List<Address> temp;
//		try{
//			temp = geocoder.getFromLocation(getLocation(index).getLatitude(),getLocation(index).getLongitude(), 1);
//		} catch(IOException e){
//			e.printStackTrace();
//			return null;
//		}
//		Log.e("KLAJKLDSJFKL", "" + temp.size());
//	
//		city = temp.get(0).getLocality();
//		return city;		
//	}
	
	
//	//Gets title of specific location at index
//	public String getLocationTitle(int index){
//		String title = "";
//		title = getCityLocation(index) + ", " + getStateLocation(index);
//		return title;
//	}
	
	//gets array of titles from locations in list
//	public String[] getLocationListTitles(){
//		String[] list = new String[numLocations];
//		for(int i = 0; i<numLocations; i++){
//			list[i] = getLocationTitle(i);
//		}
//		return list;	
//	}
	
	public int getNumLocations(){
		return numLocations;
	}

	public String getHome() {
		
		return homeLocation;
	}

	public String getGPSZip() {
		
		return currentLocationZip;
	}
}
